package com.example.synatx.lesson2;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author guoxh
 * @Date 2020/2/24 10:48
 * @Desc
 **/
public class AppleMain {

    /**
     * 行为参数化 让方法接受多种行为作为参数,并在内部使用,来完成不同的行为.
     * @param apples
     * @param p
     * @return
     */
    public static List<Apple> filterApples(List<Apple> apples,ApplePredicate p){
        List<Apple> result = new ArrayList<>();
        for(Apple apple : apples){
            if(p.test(apple)){
                result.add(apple);
            }
        }
        return result;
    }


    public void test(){
        List<Apple> appleList = new ArrayList<>();

        List<Apple> result = filterApples(appleList,new AppleHeavyWeightPredicate());
    }

    /**
     * 匿名内部类
     * 匿名内部类也有一定的缺陷:1.它往往很笨重,因为它占用了很多空间,而且不能复用;2.使用起来很让人费解.
     */
    public void test01(){
        List<Apple> appleList = new ArrayList<>();
        List<Apple> result = filterApples(appleList, new ApplePredicate() {
            @Override
            public boolean test(Apple apple) {
                return "red".equals(apple.getColor());
            }
        });
    }


    /**
     * lombda表达式
     */
    public void test02(){
        List<Apple> appleList = new ArrayList<>();
        List<Apple> result = filterApples(appleList,(Apple apple)->"red".equals(apple.getColor()));
    }

    /**
     * 将List类型抽象化
     * @param list
     * @param p
     * @param <T>
     * @return
     */
    public static <T> List<T> filter(List<T> list, IPredicate<T> p){
        List<T> result = new ArrayList<>();
        for(T t : list){
            if(p.test(t)){
                result.add(t);
            }
        }
        return result;
    }

}
